import React, { useEffect, useState } from 'react'
import { View,Image, Text,Swiper,SwiperItem } from '@tarojs/components'
import Taro, { useShareAppMessage,useReachBottom, usePageScroll } from '@tarojs/taro'
import {checkSalesMan} from "@/utils/Tools";

import './index.scss'

export default function StoreHomepage() {
  const [isTiktok,setIsTiktok] = useState(false)
  const [title,setTitle] = useState('')
  const [dy,setDy] = useState(0)
  const [categoryList,setCategoryList] = useState([])
  const [curTabs,setCurTabs] = useState(0)
  const [tabsList,setTabsList] = useState([])
  const [hotList,setHotList] = useState([])
  const [info,setInfo] = useState({})
  const [total,setTotal] = useState(0)
  const [moreStatus,setmoreStatus] = useState(null)
  const [params,setParams] = useState({
    page:1,
    pageSize:10
  })
  let moreMap = {
    'more':'加载更多',
    'loading':'加载中~',
    'no-more':'已经到底啦~',
  }
  let capsule = Taro.getMenuButtonBoundingClientRect()

  const [swiperMargin, setSwiperMargin] = useState({
    movie: 0
  })
  useEffect(()=>{
    setSwiperMargin({
      movie: Taro.getSystemInfoSync().windowWidth*220/750
    })
    if(process.env.TARO_ENV != 'weapp'){
      setIsTiktok(true)
    }
    const {router} = Taro.getCurrentInstance()
    Taro.$get(`/act/merchants/merchant-detail/${router.params.id}`,'',1).then(res=>{
      if(res.code === '1'){
        setInfo(res.content)
        setTitle(`${res.content.merchantName} | 影竞联盟`)
      }
    })
    _initData()
    checkSalesMan(router.params)
    Taro.eventCenter.on('updateLocation',(res)=>{
      _initData()
    })
  },[])
  useReachBottom(()=>{
    if(params.total > hotList.length){
      _getHotList({page:params.page+1},e=>{
        setHotList([...hotList,...e.records])
      })
    }else{
      setmoreStatus("no-more")
    }
  })
  usePageScroll(e=>{
    setDy(e.scrollTop)
  })

  function handleTabs(e){  //  切换日期
    setCurTabs(e)
    _getHotList({page:1,...tabsList[e]})
  }

  function handleToDetail(e){  ///   跳详情
    if(process.env.TARO_ENV != 'h5' && e.jumpPath){
      const url = JSON.parse(e.jumpPath)
      Taro.navigateToMiniProgram({
        appId:url.appid,
        path: url.path,
      })
      return;
    }
    Taro.navigateTo({
      url:`/mainPages/event-detail/index?id=${e.id}`
    })
  }
  ///      network
  const _initData = async (id)=>{
    const {router} = Taro.getCurrentInstance()
    Taro.$get('/act/gather/scheduleDate',{
      cityCode:Taro.getStorageSync('cityInfo').cityCode || '0',
      flag:'1',
      merchantId:router.params.id
    }).then(res=>{
      if(res.content.length){
        setTabsList(res.content)
        _getHotList({page:1,...res.content[0]})
      }
    })
  }
  const _getHotList = async (e,func)=>{  //  获取活动列表
    const loca = Taro.getStorageSync('cityInfo')
    const {router} = Taro.getCurrentInstance()
    setmoreStatus('more')
    Taro.showLoading({
      title:'加载中...'
    })
    const data = {
      merchantId:router.params.id,
      ...params,
      cityCode:loca.cityCode||0,
      page:params.page,
      pageSize:params.pageSize,
      ...e
    }
    if(loca && loca.latitude){
      Object.assign(data,{
        latitude:loca.latitude,
        longitude:loca.longitude
      })
    }
    const res = await Taro.$post('/act/aggregation/merchant',data,'1')
    if(res.code == '1'){
      setParams({...data,total:res.content.total})
      setmoreStatus('no-more')
      if(func){
        func(res.content)
        return;
      }
      setHotList(res.content.records)
    }
  }

  useShareAppMessage({
    title: title,
    path: `/mainPages/store-homepage/index?id=${Taro.getCurrentInstance().router.params?.id}`
  })
  return (
    <View className="store-homepage">
       {/* :style="{backgroundImage:info.merchantBlackGround?`url(${Taro.getMedia(info.merchantBlackGround)})`:`url('@/static/gray.jpg')`}" */}
      {isTiktok?null:<View className="uni-nav-bar" style={{paddingTop:capsule.top+'PX',height:capsule.height+'PX',backgroundColor:dy>10?'rgba(0,0,8,.8)':'transparent'}}>
        <View style={{color:'#fff',fontSize:'18px'}} className="at-icon at-icon-chevron-left" onClick={()=>{
          Taro.navigateBack().catch(()=>{
            Taro.reLaunch({
              url:'/pages/index/index'
            })
          })
        }}></View>
        <View className="bar-center dot">{title}</View>
        <View className="bar-right" style={{width:capsule.width+'PX',height:capsule.height+'PX'}}></View>
      </View>}
      <View className="homepage-header" style={{backgroundImage:`url(${Taro.getMedia(info.merchantBlackGround)})`}}>
        <View className="header-info">
          <View className='h2'>{info.merchantName} <Image src={require('@/static/verified.png')} mode="widthFix" style={{width: 13, height: 13, marginLeft: 3,verticalAlign: 'middle'}}></Image>
            <View className='p'>{info.description}</View>
          </View>
          {/* <View className='button'>+ 关注</View> */}
        </View>
        {info?.tags?.length?
        <View className="header-list">
          {info.tags.map(tag=>{
            return <Text className='span' key={tag}>{tag}</Text>
          })}
        </View>:null}
      </View>
      <View className="home-tabs">
        <View className="tabs-list not-bar">
          {tabsList?.map((item,idx)=>{
            return <View className={`tabs-item ${curTabs == idx?'active':''}` } key={item.id} onClick={()=>{handleTabs(idx)}}>
            <View className='item-h2'>{item.dateStr}</View> <Text>{item.dateDesc}</Text>
          </View>
          })}
        </View>
      </View>
      {hotList.length?<View className="home-hot">
        {/* <View className="home-title h2">热门活动</View> */}
        {hotList.map(item=>{
          return <View className="hot-list" key={item.id} onClick={()=>{handleToDetail(item)}}>
            <View className="hot-item">
              <View className="item-img">
                {item.sellOut?<View className="item-mask"><Image className="mask-img" src={require('../../static/soldout.png')}></Image></View>:null}
                <Image className="img-pic" src={Taro.getMedia(item.logoUrl)} mode="aspectFill"></Image>
              </View>
              <View className="item-info">
                <View className="dot h2">{item.locationName}</View>
                {item.tagsJson?
                <View className="info-list">
                  {item.tagsJson.map(tag=>{
                    return <Text className={`${tag.source == 'PLATFORM'?'red':''}`} key={tag.tagName}>{tag.tagName}</Text>
                  })}
                </View>:null}
                <View className="h4 dot"><Image src={require('@/static/icon_calendar.png')} /> {item.dateStr}</View>
                {item.hallName?<View className="h4 dot"><Image src={require('@/static/icon-space.png')} /> {item.hallName}</View>:null}
                <View className="h4"><Image src={require('@/static/icon_map-pin.png')} /> {item.distance?item.distance:''}&nbsp;<Text className='dot'>{item.locationAddress}</Text></View>
                {item.establishTickets>0?
                <View className="list-item">
                  {item.isEstablish?<>
                  <Image className='image' src={require('@/static/checked-true.svg')}></Image>
                  <Text className='strong'>已成团</Text>
                  <Text className='span'>已报名{item.recordNum}人{item.maxTickets?`（满场${item.maxTickets}人）`:null}</Text>
                  </>:<>
                  <Text className='strong'>{item.establishTickets}人开场{item.recordNum>0?'，已组'+item.recordNum+'人':''}</Text>
                  <Text className='span'>{item.remainTimeDesc}</Text>
                  </>}
                </View>:null}
              </View>
            </View>
            <View className="item-footer">
              <View className="footer-merchant">
                <Image className='logo' src={item.merchantUrl} />
                <View>{item.merchantName}</View>
                <Image className='icon' src={require('@/static/verified.png')} />
              </View>
              <View className="footer-price">¥ <Text style={{fontSize:18,margin:"0 1px"}}>{item.price}</Text> {item.areaPrice=='2'?'起':''}</View>
            </View>
          </View>
        })}
      </View>:<View className='var-empty'>
        <View className="h2">没有场次安排</View>
        <View className="p">后续会发布新的活动场次，敬请期待哦~</View>
      </View>}
      {hotList.length && moreStatus?<View className="var-more">{moreMap[moreStatus]}</View>:null}
    </View>
  )
}
